#!/bin/bash
# Author: Mickeywaugh@qq.com
# Description: MySQL备份脚本

echo "MySQL备份脚本 by Mickeywaugh"
echo "======================================================================="
echo "环境准备"
apps="mysql-client gzip grep sed"

if command -v apt-get &>/dev/null; then
  apt-get install -y $apps
elif command -v yum &>/dev/null; then
  yum install -y $apps
else
  echo "未找到支持的包管理工具"
fi

# 获取当前脚本的绝对路径
SCRIPT_PATH=$(readlink -f "$0")
# 获取脚本所在目录
SCRIPT_DIR=$(dirname "$SCRIPT_PATH")
# 使用脚本所在目录作为基础路径
conf="$SCRIPT_DIR/.my.cnf"

if [ -f "$conf" ]; then
  mysql_backup_dir=$(grep -e '^backupDir=' $conf | awk -F '=' '{print $2}')
  #是否开启过期备份删除 ON为开启 OFF为关闭
  expire_backup_delete=$(grep -e '^expireDelete=' $conf | awk -F '=' '{print $2}')
  #过期时间天数 默认为7天,此项只有在expire_backup_delete开启时有效
  expire_days=$(grep -e '^expireDays=' $conf | awk -F '=' '{print $2}')
  dbs=$(grep -e '^dbs=' $conf | cut -d '=' -f2 | sed 's/ /,/g')
  IFS=',' read -r -a dbs <<<"$dbs"
else
  echo "ERROR: conf file not found! backup stop!"
  exit 1
fi

# 本行开始以下不需要修改

backup_time=$(date +%Y%m%d%H%M) #定义备份详细时间
backup_Ymd=$(date +%Y-%m-%d)    #定义备份目录中的年月日时间

backup_dir=$mysql_backup_dir/$backup_Ymd         #备份文件夹全路径
welcome_msg="Welcome to use MySQL backup tools!" #欢迎语

echo $welcome_msg
echo "Testing MySQL connection..."
# 连接到mysql数据库，无法连接则备份退出
mysql --defaults-extra-file=$conf -e "SELECT VERSION();"

flag=$(echo $?)
if [ $flag != "0" ]; then
  echo "ERROR:Can't connect mysql server! backup stop!"
  exit
else
  echo "MySQL connect ok! Please wait......"
  # 判断有没有定义备份的数据库，如果定义则开始备份，否则退出备份
  if [ "$dbs" != "" ]; then
    #dbnames=$(cut -d ',' -f1-5 $backup_database)
    # echo "arr is (${dbs[@]})"
    for dbname in ${dbs[@]}; do
      echo "database $dbname backup start..."
      $(mkdir -p $backup_dir)
      $(mysqldump --defaults-extra-file=$conf $dbname | gzip >$backup_dir/$dbname-$backup_time.sql.gz)
      flag=$(echo $?)
      if [ $flag == "0" ]; then
        echo "database $dbname success backup to $backup_dir/$dbname-$backup_time.sql.gz"
      else
        echo "database $dbname backup fail!"
      fi

    done
  else
    echo "ERROR:No database to backup! backup stop"
    exit
  fi
  # 如果开启了删除过期备份，则进行删除操作
  if [ "$expire_backup_delete" == "ON" -a "$mysql_backup_dir" != "" ]; then
    #`find $mysql_backup_dir/ -type d -o -type f -ctime +$expire_days -exec rm -rf {} \;`
    $(find $mysql_backup_dir/ -type d -mtime +$expire_days | xargs rm -rf)
    echo "Expired backup data delete complete!"
  fi
  echo "All database backup success!"
  exit
fi
